/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package chatqueue;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.naming.InitialContext;

/**
 *
 * @author bjugis
 */
@MessageDriven(mappedName = "jms/chatQueue", activationConfig =  {
        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
        @ActivationConfigProperty(propertyName = "subscriptionDurability", propertyValue = "Durable"),
        @ActivationConfigProperty(propertyName = "clientId", propertyValue = "ChatQueueMB"),
        @ActivationConfigProperty(propertyName = "subscriptionName", propertyValue = "ChatQueueMB")
    })
public class ChatQueueMB implements MessageListener {
    @Resource(mappedName = "jms/chatQueue")
    private Topic chatQueue;
    @Resource(mappedName = "jms/chatQueueFactory")
    private ConnectionFactory chatQueueFactory;
    @EJB
    private ChatQueueEJBRemote chatQueueEJB;
    
    public ChatQueueMB() {

    }

    public void onMessage(Message message) {
        ObjectMessage msg = null;
        
        if(message instanceof ObjectMessage) {
            msg = (ObjectMessage) message;
            ChatQueuePackage queueObj = null;
            try {
                queueObj =  (ChatQueuePackage) msg.getObject();
            } catch(Exception e) {
                System.out.println(e.getMessage());
            }

            
            if(queueObj.addToQueue) {
                try {
                    if(chatQueueEJB.getQueueNumber(message.getJMSReplyTo()) < 0)
                        chatQueueEJB.addClientToQueue(message.getJMSReplyTo());
                    ChatQueuePackage cqp = new ChatQueuePackage(false, null, chatQueueEJB.getQueueNumber(message.getJMSReplyTo()));
                    this.sendJMSMessage(message.getJMSReplyTo(), null , cqp);
                } catch(Exception e) {
                    System.out.println(e.getMessage());
                }
            }
            else {
                ChatQueuePackage cqp = new ChatQueuePackage(false, "Velkommen!");
                try {
                    if(chatQueueEJB.peek() != null && !chatQueueEJB.peek().toString().equalsIgnoreCase(message.getJMSReplyTo().toString())) {
                        Destination destination = chatQueueEJB.getNextInQueue();
                        this.sendJMSMessage(destination, message.getJMSReplyTo() , cqp);
                        this.sendJMSMessage(message.getJMSReplyTo(), destination , cqp);
                    }

                } catch(Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }

    private Message createJMSMessageForjmsChatQueue(Session session, Destination replyTo, ChatQueuePackage messageData) throws JMSException {
        // TODO create and populate message to send
        ObjectMessage tm = session.createObjectMessage();
        tm.setJMSReplyTo(replyTo);
        tm.setObject(messageData);
        return tm;
    }

    private void sendJMSMessage(Destination destination, Destination replyTo,  ChatQueuePackage messageData) throws Exception {
        Connection connection = null;
        Session session = null;
        try {
            connection = chatQueueFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            //Destination clientDestination = (Destination) initContext.lookup(destination);
            MessageProducer messageProducer = session.createProducer(destination);
            messageProducer.send(createJMSMessageForjmsChatQueue(session, replyTo, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
/*
    private void sendJMSMessageToChatQueue(ChatQueuePackage messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = chatQueueFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(chatQueue);
            messageProducer.send(createJMSMessageForjmsChatQueue(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }   
 */
}
